/**
 *单位(派出所)下拉
 */

import { Select, SelectProps } from 'antd';
import { memo, useImperativeHandle, useState } from 'react';

import { ILawsRef } from '../../types';
import { useGetUnitBypcs } from '../../service/unit-service';

interface IRoleSelectProps extends SelectProps<number> {
    handleChange: (value: string) => void;
    onRef?: React.MutableRefObject<ILawsRef | undefined>;
    unitType: number;
}

const UnitSelect = ({ handleChange, onRef, unitType }: IRoleSelectProps) => {
    const { isLoading, isError, data: dataSource } = useGetUnitBypcs({ unitType });

    const [val, setVal] = useState<string>();
    const onChange = (value: string) => {
        setVal(value);
        handleChange(value);
    };

    /**向外暴露的重置方法 */
    useImperativeHandle(onRef, () => ({
        rest: () => {
            setVal(undefined);
        },
        fill: (unitId) => {
            setVal(unitId);
        },
        getData: () => {
            return val;
        }
    }));
    return (

        <Select placeholder={'请选择单位'} value={val} onChange={onChange} loading={isLoading} allowClear>
            {isError
                ? null
                : dataSource?.map((data) => {
                    return <Select.Option key={data.unitId} value={data.unitId}>
                        {data.unitShortName}
                    </Select.Option>
                })}
        </Select >

    );
};


export default memo(UnitSelect)